'use strict';

const Controller = require('egg').Controller;

/**
 * @controller 任务 task
 */
class TasksController extends Controller {
  /**
   * @apikey
   * @summary 获取 任务
   * @description 获取 任务
   * @request query string name task名
   * @request query number limit limit
   * @request query number offset offset
   * @router get /api/v1/tasks/list
   */
  async findAll() {
    const {
      ctx,
      service,
      app: { lodash },
    } = this;
    const rules = {
      executor_ids: {
        type: 'array',
        required: false,
        itemType: 'number',
        description: '执行者IDs',
        example: [1, 2],
      },
      creator_ids: {
        type: 'array',
        required: false,
        itemType: 'number',
        description: '创建者IDs',
        example: [1, 2],
      },
      task_priority_ids: {
        type: 'array',
        required: false,
        itemType: 'number',
        description: '优先级IDs',
        example: [1, 2],
      },
      task_state_ids: {
        type: 'array',
        required: false,
        itemType: 'number',
        description: '执行状态IDs',
        example: [1, 2],
      },
    };
    const roles2 = {
      date_start_created: {
        type: 'dateTime',
        required: false,
        description: '创建的开始时间',
        example: 'YYYY-MM-DD HH:mm:ss',
      },
      date_end_created: {
        type: 'dateTime',
        required: false,
        description: '创建的结束时间',
        example: 'YYYY-MM-DD HH:mm:ss',
      },
      participator_id: {
        type: 'number',
        required: false,
        description: '参与者ID',
        example: 1,
      },
    };
    const queries = Object.assign({}, ctx.query);
    for (const key in rules) {
      const data = ctx.query[key];
      if (data) {
        // 处理数组参数，如 executor_ids=1 或 executor_ids=1,2,3
        if (rules[key].type === 'array') {
          if (lodash.isArray(data)) {
            queries[key] = lodash.map(data, lodash.parseInt);
          } else {
            // 如果是字符串，按逗号分割并转换为数字数组
            queries[key] = data.toString().split(',').map(item => parseInt(item.trim())).filter(item => !isNaN(item));
          }
        }
      }
    }
    debugger
    const { allRule, query } = ctx.helper.tools.findAllParamsDeal({
      rule: ctx.rule.taskPutBodyReq,
      queryOrigin: queries,
      ruleOther: { ...rules, ...roles2 },
    });

    ctx.validate(allRule, query);
    const res = await service.tasks.findAll(query);
    ctx.helper.body.SUCCESS({ ctx, res });
  }

}

module.exports = TasksController;